/**
 * 用户登录页面
 */
import React, { useState } from 'react';
import { Form, Input, Button, Card, message, Checkbox } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { history, useModel } from '@umijs/max';
import { login } from '@/services/auth';
import { setToken, setUserInfo } from '@/utils/auth';
import styles from './index.less';

interface LoginFormValues {
  username: string;
  password: string;
  remember?: boolean;
}

const Login: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const { initialState, setInitialState } = useModel('@@initialState');

  const handleSubmit = async (values: LoginFormValues) => {
    setLoading(true);
    try {
      const result = await login({
        username: values.username,
        password: values.password,
      });

      // 保存认证信息
      setToken(result.access_token);
      setUserInfo(result.user_info);

      // 更新全局状态
      setInitialState((s) => ({
        ...s,
        currentUser: result.user_info,
      }));

      message.success('登录成功！');
      
      // 跳转到首页
      const urlParams = new URL(window.location.href).searchParams;
      history.push(urlParams.get('redirect') || '/welcome');
    } catch (error: any) {
      message.error(error.message || '登录失败，请检查用户名和密码');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <div className={styles.top}>
          <div className={styles.header}>
            <img alt="logo" className={styles.logo} src="/logo.svg" />
            <span className={styles.title}>邮件统一发送平台</span>
          </div>
          <div className={styles.desc}>
            高效、安全、便捷的邮件发送解决方案
          </div>
        </div>

        <div className={styles.main}>
          <Card className={styles.loginCard}>
            <Form
              name="login"
              size="large"
              onFinish={handleSubmit}
              autoComplete="off"
            >
              <Form.Item
                name="username"
                rules={[
                  { required: true, message: '请输入用户名!' },
                  { min: 2, message: '用户名至少2个字符!' },
                ]}
              >
                <Input
                  prefix={<UserOutlined />}
                  placeholder="用户名"
                  autoComplete="username"
                />
              </Form.Item>

              <Form.Item
                name="password"
                rules={[
                  { required: true, message: '请输入密码!' },
                  { min: 6, message: '密码至少6个字符!' },
                ]}
              >
                <Input.Password
                  prefix={<LockOutlined />}
                  placeholder="密码"
                  autoComplete="current-password"
                />
              </Form.Item>

              <Form.Item>
                <Form.Item name="remember" valuePropName="checked" noStyle>
                  <Checkbox>记住我</Checkbox>
                </Form.Item>
              </Form.Item>

              <Form.Item>
                <Button
                  type="primary"
                  htmlType="submit"
                  loading={loading}
                  block
                >
                  登录
                </Button>
              </Form.Item>
            </Form>

            <div className={styles.other}>
              <div className={styles.tips}>
                <div>默认管理员账号：admin</div>
                <div>默认密码：admin123</div>
              </div>
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
};

export default Login;
